package com.vxfly.helioscamera.Activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vxfly.helioscamera.SDKAPI.CameraProperties;
import com.vxfly.helioscamera.adapter.WifiListAdapter;
import com.vxfly.helioscamera.baseItems.WifiSsidPwd;
import com.vxfly.helioscamera.camera.MyCamera;
import com.vxfly.helioscamera.function.SystemCheckTools;
import com.vxfly.helioscamera.function.WifiCheck;
import com.vxfly.helioscamera.function.WifiHistory;
import com.vxfly.helioscamera.global.App.ExitApp;
import com.vxfly.helioscamera.global.App.GlobalInfo;
import com.vxfly.helioscamera.global.App.PropertyId;
import com.vxfly.helioscamera.log.WriteLogToDevice;
import com.vxfly.helioscamera.R;

public class WifiConnectActivity extends Activity {

	private Button connectWifi;
	private ListView wifiListView;
	private List<ScanResult> wifiList;
	private WifiCheck wifiCheck;
	private WifiListAdapter wifiListAdapter;
	private ImageView refresh;
	private TextView back;
	private TextView ssid;
	private EditText password;
	private int reconnectTime;
	private ScanResult currentChooseWifi;
	public static final int CONNECT_WIFI_SUCCESS = 0;
	public static final int CONNECT_WIFI_FAIL = 1;
	public static final int CONNECT_DEVICE_SUCCESS = 2;
	public static final int CONNECT_DEVICE_FAIL = 3;
	public static final int REFRESH_TIME_OUT = 4;
	private ProgressDialog progressDialog;
	private MyHandler myHandler;
	private Timer timer;
	private MyCamera currentCamera;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wifi_connect);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		// do not display menu bar
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		GlobalInfo.getInstance().setCurrentApp(WifiConnectActivity.this);
		ExitApp.getInstance().addActivity(this);
		wifiCheck = new WifiCheck();
		myHandler = new MyHandler();

		ssid = (TextView) findViewById(R.id.wifi_ssid);
		password = (EditText) findViewById(R.id.password);

		WifiManager mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifi.getConnectionInfo();
		if (wifiInfo != null) {
			String tempSsid = wifiInfo.getSSID();
			tempSsid = tempSsid.replaceAll("\"", "");
			ssid.setText(tempSsid);
			String temp = WifiHistory.getPwdByName(tempSsid, WifiConnectActivity.this);
			if (temp != null) {
				password.setText(temp);
			} else {
				password.setText("");
			}
		}
		// progressBar = (ProgressBar)
		// findViewById(R.id.progressBar_connect_wifi);

		wifiListView = (ListView) findViewById(R.id.choose_wifi_list);
		//wifiList = wifiCheck.getWifiList();
		//JIRA ICOM-1991 ICOM-1992 Begin Add by b.jiang 2015-09-21
		wifiList = wifiCheck.getWifiListWithStartString();
		//JIRA ICOM-1991 ICOM-1992 End Add by b.jiang 2015-09-21
		wifiListAdapter = new WifiListAdapter(WifiConnectActivity.this, wifiList);
		wifiListView.setAdapter(wifiListAdapter);

		connectWifi = (Button) findViewById(R.id.conenct_wifi);
		connectWifi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (currentChooseWifi == null) {
					Toast.makeText(WifiConnectActivity.this, R.string.dialog_select_wifi, Toast.LENGTH_LONG).show();
					return;
				}
				if (password.getText().toString().length() < 8 || password.getText().toString().length() > 10) {
					Toast.makeText(WifiConnectActivity.this, R.string.password_limit, Toast.LENGTH_LONG).show();
					return;
				}
				WifiHistory.save(new WifiSsidPwd(ssid.getText().toString(), password.getText().toString()), WifiConnectActivity.this);
				showProgressDialog(WifiConnectActivity.this.getString(R.string.dialog_init_network));
				wifiCheck.connectWifi(ssid.getText().toString(), password.getText().toString(), wifiCheck.getSecurity(currentChooseWifi));
				reconnectTime = 0;
				final Timer connectTimer = new Timer();
				TimerTask task = new TimerTask() {

					@Override
					public void run() {
						if (wifiCheck.isWifiConnected(WifiConnectActivity.this, currentChooseWifi.SSID) == true) {
							WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == true");
							// sendOkMsg(CONNECT_NEW_WIFI_SUCCESS);
							if (connectTimer != null) {
								connectTimer.cancel();
							}
							myHandler.obtainMessage(CONNECT_WIFI_SUCCESS).sendToTarget();
							return;
						} else {
							WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == false  reconnectTime ="
									+ reconnectTime);
							reconnectTime++;
							if (reconnectTime >= 20) {
								if (connectTimer != null) {
									connectTimer.cancel();
								}
								// wifiList.remove(0);
								// sendOkMsg(CONNECT_NEXT_WIFI);
								myHandler.obtainMessage(CONNECT_WIFI_FAIL).sendToTarget();
								return;
							}
						}
					}
				};
				connectTimer.schedule(task, 0, 3000);
			}
		});

		refresh = (ImageView) findViewById(R.id.refresh);
		refresh.setOnClickListener(new OnClickListener() {

			private TimerTask refreshTask;

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				showProgressDialog(WifiConnectActivity.this.getString(R.string.dialog_refreshing));
				timer = new Timer(true);
				refreshTask = new TimerTask() {

					@Override
					public void run() {

						WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "appstart run:");
						myHandler.obtainMessage(REFRESH_TIME_OUT).sendToTarget();

					}
				};
				timer.schedule(refreshTask, 5000);
			}
		});

		back = (TextView) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		wifiListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				ssid.setText(wifiList.get(arg2).SSID);
				currentChooseWifi = wifiList.get(arg2);
				String temp = WifiHistory.getPwdByName(wifiList.get(arg2).SSID, WifiConnectActivity.this);
				if (temp != null) {
					password.setText(temp);
				} else {
					password.setText("");
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.wifi_connect, menu);
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_HOME:
			ExitApp.getInstance().exit();
			break;
		case KeyEvent.KEYCODE_BACK:
			finish();
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}

		return true;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		GlobalInfo.getInstance().setCurrentApp(WifiConnectActivity.this);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		if (SystemCheckTools.isApplicationSentToBackground(WifiConnectActivity.this) == true) {
			ExitApp.getInstance().exit();
		}
		super.onStop();
	}

	private class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CONNECT_WIFI_SUCCESS:
				WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_SUCCESS");
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				showProgressDialog(WifiConnectActivity.this.getString(R.string.dialog_connecting_to_cam));
				initAPP(ssid.getText().toString());
				break;
			case CONNECT_WIFI_FAIL:
				WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_FAIL");
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				Toast.makeText(WifiConnectActivity.this, R.string.dialog_connect_failed, Toast.LENGTH_LONG).show();
				break;
			case CONNECT_DEVICE_SUCCESS:
				WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_SUCCESS");
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				GlobalInfo.getInstance().setSsid(ssid.getText().toString());
				Intent intent = new Intent(WifiConnectActivity.this, Main.class);
				startActivity(intent);
				break;
			case CONNECT_DEVICE_FAIL:
				WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_FAIL");
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				Toast.makeText(WifiConnectActivity.this, R.string.dialog_connect_failed, Toast.LENGTH_LONG).show();
				break;
			case REFRESH_TIME_OUT:
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				wifiListAdapter.notifyDataSetChanged();
				//wifiList = wifiCheck.getWifiList();
				//JIRA ICOM-1991 ICOM-1992 Begin Add by b.jiang 2015-09-21
				wifiList = wifiCheck.getWifiListWithStartString();
				//JIRA ICOM-1991 ICOM-1992 Begin Add by b.jiang 2015-09-21
				wifiListAdapter = new WifiListAdapter(WifiConnectActivity.this, wifiList);
				wifiListView.setAdapter(wifiListAdapter);
				break;
			}

		}
	}

	private void showProgressDialog(String message) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
		progressDialog = new ProgressDialog(WifiConnectActivity.this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage(message);
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	private void initAPP(String ssid) {
		WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == true");
		currentCamera = new MyCamera();
		if (currentCamera.getSDKsession().prepareSession() == false) {
			// redirectToExit();
			myHandler.obtainMessage(CONNECT_DEVICE_FAIL).sendToTarget();
			return;
		}
		if (currentCamera.getSDKsession().checkWifiConnection() == true) {
			GlobalInfo.getInstance().addCamera(currentCamera);
			GlobalInfo.getInstance().setCurrentCamera(currentCamera);
			currentCamera.initCamera();
			if (CameraProperties.getInstance().hasFuction(PropertyId.CAMERA_DATE)) {
				long time = System.currentTimeMillis();
				Date date = new Date(time);
				SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMdd HHmmss");
				String temp = myFmt.format(date);
				temp = temp.replaceAll(" ", "T");
				temp = temp + ".0";
				CameraProperties.getInstance().setCameraDate(temp);
			}
//			CameraInfoHistory.save(new CameraStoreInfo(CameraProperties.getInstance().getCameraName(), currentCamera.getSDKsession()
//					.getUId(), CameraProperties.getInstance().getCameraPasswordNew()), WifiConnectActivity.this);
			currentCamera.setMyMode(1);
			myHandler.obtainMessage(CONNECT_DEVICE_SUCCESS).sendToTarget();
			return;
		} else {
			WriteLogToDevice.writeLog("[ERROR] -- AppStartActivity: ", "..........checkWifiConnection  fail");
			myHandler.obtainMessage(CONNECT_DEVICE_FAIL).sendToTarget();
			return;
		}
	}

	private void showDialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(WifiConnectActivity.this);
		builder.setMessage(message);
		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		AlertDialog dialog = builder.create();
		dialog.setCancelable(false);
		dialog.show();
	}
}
